<template>
  <div class="wrapper">
    <div shadow="never" class="verify-card">
      <el-form
        label-position="top"
        :model="ruleForm"
        class="verify-file"
        label-width="150px"
        :inline="true"
        :rules="rules"
        ref="ruleForm"
        :disabled="disable"
        :key="ruleForm.id"
      >
        <el-row>
          <el-form-item label="区域" prop="region">
            <el-select v-model="ruleForm.region" filterable clearable>
              <el-option
                v-for="website in websiteData"
                :key="website.id"
                :label="website.name"
                :value="website.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="省市区" prop="addr">
            <el-cascader
              v-model="ruleForm.addr"
              placeholder="请选择地区"
              filterable
              clearable
              :options="areaData"
              :props="{
                value: 'id',
                label: 'name',
                children: 'next_level_data',
              }"
              @change="handleAddrChange"
              ref="cascaderAddr"
            >
            </el-cascader>
          </el-form-item>
          <el-form-item label="详细地址" prop="place_address">
            <el-input v-model="ruleForm.place_address"></el-input>
          </el-form-item>
          <el-form-item label="面积" prop="area">
            <el-input v-model="ruleForm.area"></el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="温度控制范围" prop="temp_range">
            <el-input v-model="ruleForm.temp_range"></el-input>
          </el-form-item>
          <!-- <el-form-item label="验证时长（小时）" prop="verify_duration">
                    <el-input v-model="ruleForm.verify_duration"></el-input>
                </el-form-item> -->
          <el-form-item label="验证时间" prop="verify_time">
            <el-date-picker
              style="width: 215px"
              @change="handleTimeChange"
              v-model="ruleForm.verify_time"
              type="daterange"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="timestamp"
              :picker-options="pickerOptions"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="验证类型" prop="verify_type">
            <el-input v-model="ruleForm.verify_type"></el-input>
          </el-form-item>
          <el-form-item label="验证公司" prop="verify_company">
            <el-input v-model="ruleForm.verify_company"></el-input>
          </el-form-item>
        </el-row>
        <el-form-item label="计划" prop="plan">
          <el-input v-model="ruleForm.plan"></el-input>
        </el-form-item>
        <el-form-item label="验证主体" prop="verify_subject">
          <el-input v-model="ruleForm.verify_subject"></el-input>
        </el-form-item>
        <el-form-item label="验证状态" prop="status">
          <el-radio-group v-model="ruleForm.status">
            <el-radio :label="1">有效</el-radio>
            <el-radio :label="2">无效</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="负责人" prop="principal">
          <el-select v-model="ruleForm.principal" filterable clearable>
            <el-option
              v-for="handler in staffData"
              :key="handler.id"
              :label="handler.name"
              :value="handler.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="上传报告" prop="verify_reports" ref="uploadRef">
          <UploadLink
            style="width: 215px"
            :files.sync="ruleForm.verify_reports"
          ></UploadLink>
        </el-form-item>
      </el-form>
    </div>
    <div class="operation-footer">
      <div class="footer-wrap">
        <el-button size="small" @click="handleClickClose">关闭</el-button>
        <template v-if="mode !== 'detail'">
          <el-button size="small" type="primary" @click="handleSubmit"
            >保存</el-button
          >
        </template>
      </div>
    </div>
  </div>
</template>

<script>
import {
  VerifyRecordCreate,
  VerifyRecordUpdate,
  VerifyRecordDetail,
} from "@/api/qms.js";
import { timestamp10 } from "@/utils/mUtils";
import { uploading, regionList } from "@/page/material/common/common";
import { reqWebsiteList } from "@/api/waybill";
import { AdminBox } from "@/api/customer";
import UploadLink from "@/components/uploadFile/uploadLink.vue";

export default {
  name: "verifyEdit",
  components: { UploadLink },
  props: ["validation_class", "mode", "id"],
  data() {
    return {
      ruleForm: {
        region: "", // 区域
        place_province: 0, // 地点省份
        place_city: 0, // 地点城市
        place_distirct: 0, // 地点区县
        place_address: "", // 地点详细地址
        area: "", //面积
        temp_range: "", // 温度控制范围
        verify_time: [], // 验证时间
        verify_type: "", // 验证类型
        verify_company: "", // 验证公司
        plan: "", // 计划
        verify_subject: "", // 验证主体
        status: 1, // 验证状态, 1:有效，2:无效。
        principal: "", // 负责人
        verify_reports: [],
      },
      rules: {
        region: [{ required: true, message: "请选择区域", trigger: "change" }],
        addr: [{ required: true, message: "请选择省市区", trigger: "change" }],

        place_address: [
          { required: true, message: "请输入详细地址", trigger: "blur" },
        ],
        temp_range: [
          { required: true, message: "请输入温度控制范围", trigger: "blur" },
        ],
        verify_time: [
          { required: true, message: "请选择验证时间", trigger: "change" },
        ],
        area: [{ required: true, message: "请输入面积", trigger: "blur" }],
        verify_type: [
          { required: true, message: "请输入验证类型", trigger: "blur" },
        ],
        verify_company: [
          { required: true, message: "请输入验证公司", trigger: "blur" },
        ],
        plan: [{ required: true, message: "请输入计划", trigger: "blur" }],
        verify_subject: [
          { required: true, message: "请输入验证主体", trigger: "blur" },
        ],
        status: [
          { required: true, message: "请选择验证状态", trigger: "change" },
        ],
        principal: [
          { required: true, message: "请选择负责人", trigger: "change" },
        ],
        verify_reports: [
          { required: true, message: "请上传报告", trigger: "change" },
        ],
      },
      areaData: [],
      websiteData: [],
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      staffData: [],
    };
  },
  computed: {
    disable() {
      return this.mode === "detail";
    },
  },
  watch: {
    mode: {
      handler(newValue, oldValue) {
        this.handleChangeMode();
      },
      immediate: true,
    },
    "ruleForm.verify_reports": function (val) {
      this.$refs.uploadRef.clearValidate();
    },
  },
  mounted() {
    regionList(0).then((res) => {
      this.areaData = res.data;
    });
    reqWebsiteList({ branch_type: "3" }).then((res) => {
      this.websiteData = res.data;
    });
    AdminBox({
      user_type: "0",
    }).then((res) => {
      this.staffData = res.data;
    });
  },

  methods: {
    handleClickClose() {
      this.$router.push({
        name: "verifylist",
        query: {
          type: this.validation_class,
        },
      });
    },
    handleTimeChange(val) {
      if (val) {
        this.ruleForm.verify_start_time = timestamp10(val[0]) * 1;
        this.ruleForm.verify_end_time = timestamp10(val[1]) * 1;
      } else {
        this.ruleForm.verify_start_time = undefined;
        this.ruleForm.verify_end_time = undefined;
      }
    },
    // 选择地址
    handleAddrChange(val) {
      // console.log(val, 'val');
      if (val) {
        this.ruleForm.place_province = Number(val[0]);
        this.ruleForm.place_city = Number(val[1]);
        this.ruleForm.place_distirct = Number(val[2]);
      }
    },
    handleChangeMode() {
      if (this.mode === "add") {
      } else if (this.mode === "detail" || this.mode === "edit") {
        this.getDetail();
      }
    },
    getDetail() {
      VerifyRecordDetail({
        id: this.id * 1,
      }).then((res) => {
        const data = res.data.data;
        if (data.place_province) {
          data.addr = [
            data.place_province,
            data.place_city,
            data.place_distirct,
          ];
        }
        if (data.verify_start_time) {
          data.verify_time = [
            data.verify_start_time * 1000,
            data.verify_end_time * 1000,
          ];
        }
        data.checkout_date = data.checkout_date * 1000 || "";
        data.effective_date = data.effective_date * 1000 || "";
        this.ruleForm = data;
      });
    },
    handleSubmit() {
      this.$refs["ruleForm"].validate((valid) => {
        if (!valid) return;
        const _ruleForm = {
          ...this.ruleForm,
          region: this.ruleForm.region * 1,
          checkout_date: timestamp10(this.ruleForm.checkout_date) * 1,
          effective_date: timestamp10(this.ruleForm.effective_date) * 1,
          validation_class: this.validation_class,
        };
        if (this.mode === "add") {
          VerifyRecordCreate(_ruleForm).then((res) => {
            if (res.code === 10000) {
              this.$message({
                type: "success",
                message: "保存成功",
              });
              setTimeout(() => {
                this.$router.push({
                  name: "verifylist",
                  query: {
                    type: this.validation_class,
                  },
                });
              }, 200);
            }
          });
        } else {
          VerifyRecordUpdate(_ruleForm).then((res) => {
            if (res.code === 10000) {
              this.$message({
                type: "success",
                message: "修改成功",
              });
              setTimeout(() => {
                this.$router.push({
                  name: "verifylist",
                  query: {
                    type: this.validation_class,
                  },
                });
              }, 200);
            }
          });
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.wrapper {
  // min-height: 100vh;
  .form-container {
    box-sizing: border-box;
    padding: 10px;
    padding-top: 10px;
    position: relative;
  }

  .verify-card {
    box-sizing: border-box;
    background: #fff;
    // margin: 8px;
    border-radius: 5px;
    padding: 10px;
  }

  .verify-file {
    .el-input {
      width: 215px;
    }

    .el-radio-group,
    .el-select,
    .el-cascader {
      width: 215px;
    }

    .el-textarea {
      width: 400px;
    }

    /deep/ .el-form-item {
      margin-right: 30px !important;
    }
  }

  .box-card {
    width: 450px;

    /deep/.el-card__body {
      padding: 10px;
    }
  }

  .info-card {
    border: none;
    margin-bottom: 10px;

    &.left {
      width: 60%;
    }

    &.right {
      width: 39.5%;
      margin-left: 10px;
    }
  }

  .card-wrap {
    display: flex;
    justify-content: space-around;
    min-height: 200px;

    .info-card {
      display: inline-block;
      min-height: 100%;
    }
  }

  .file-list {
    width: 100%;
    // padding-top: 10px;

    li {
      // width: 60%;
      display: flex;
      // justify-content: space-between;
      padding-bottom: 5px;
      align-items: center;

      .file-icon {
        cursor: pointer;
        font-size: 14px;

        &:hover {
          color: #409eff;
          // transform: scale(1.5);
          // transition: all ease 0.2s;
        }
      }

      .link-text {
        justify-content: flex-start;

        /deep/.el-link--inner {
          width: 400px;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }
      }
    }
  }

  .seal-img {
    width: 100%;

    img {
      width: 100%;
    }
  }
}
</style>